#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- mode: python -*-

import os, time

def update_failed_request (request_id):
  path = os.path.abspath('failedreqs')

  if not os.path.exists(path):
    os.mkdir(path, 0755)

  path = os.path.join(path, request_id)

  try:
    f = open(path, 'r+')
    n = int(f.read()) + 1
    f.seek(0)
    f.write(str(n))
    f.close()
    os.utime(path, None)
  except IOError:
    try:
      f = open(path, 'w')
      f.write('1')
      f.close()
    except:
      pass
  except:
    pass

def is_failed_request (request_id, expired_seconds):
  path = os.path.abspath(os.path.join('failedreqs', request_id))

  result = False

  try:
    f = open(path)

    if int(f.read()) >= 3:
      if os.path.getatime(path) + expired_seconds >= time.time():
        result = True

    f.close()
  except:
    pass

  return result
